﻿using AuthCenter.Domain;
using AuthCenter.ErorCode;
using AuthCenter.Infrastructure;
using AuthCenter_API.Read.Applications.Commands.RBAC;
using AuthCenter_API.Read.Dtos;
using MediatR;

namespace AuthCenter_API.Read.Applications.CommandHandlers.RBAC
{
    public class FantianUserNameCommandHandler : IRequestHandler<FantianUserNameCommand, APIResult<UserNameDto>>
    {
        private readonly IBaseRepository<UserModel> _userRepository;
        private readonly IBaseRepository<UserRoleModel> _userroleRepository;

        public FantianUserNameCommandHandler(IBaseRepository<UserModel> userRepository, IBaseRepository<UserRoleModel> userroleRepository)
        {
            _userRepository = userRepository;
            _userroleRepository = userroleRepository;
        }

        public Task<APIResult<UserNameDto>> Handle(FantianUserNameCommand request, CancellationToken cancellationToken)
        {
            APIResult<UserNameDto> result = new APIResult<UserNameDto>();
            result.Code = APIEnum.QueryFail;
            result.Message = APIEnum.QueryFail.Desc();
            UserNameDto dto=new UserNameDto();
            var userList = _userroleRepository.GetAll().Where(x => x.RoleId == request.RoleId).Select(x => Convert.ToInt32(x.UserId)).ToList();
            if(userList.Count()!=0)
            {
                result.Code = APIEnum.QuerySuccess;
                result.Message = "获取成功";
                var depIdList = (_userRepository.GetAll().FirstOrDefault(x => x.Id == userList[0])!).DepId;
                dto.IdList = userList;
                dto.DepId=Convert.ToInt32(depIdList);
                dto.UserList = _userRepository.GetAll().Where(x => userList.Contains(x.Id)).ToList();
                result.Data = dto;
                return Task.FromResult(result);
            }
            result.Data = dto;
            return Task.FromResult(result);
        }
    }
}
